﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using XCode;
using NewLife.YWS.Entities;

namespace NewLife.YWS.Entities
{
	/// <summary>
	/// 交易记录
	/// </summary>
	public partial class Record : Entity<Record>
	{
		#region 对象操作
		//基类Entity中包含三个对象操作：Insert、Update、Delete
		//你可以重载它们，以改变它们的行为
		//如：
		/*
		/// <summary>
		/// 已重载。把该对象插入到数据库。这里可以做数据插入前的检查
		/// </summary>
		/// <returns>影响的行数</returns>
		public override Int32 Insert()
		{
			return base.Insert();
		}
		 * */
		#endregion
		
		#region 扩展属性
		//TODO: 本类与哪些类有关联，可以在这里放置一个属性，使用延迟加载的方式获取关联对象

		private Customer _Customer;
		/// <summary>该交易记录所对应的客户</summary>
		public Customer Customer
		{
			get
			{
				if (_Customer == null && CustomerID > 0 && !Dirtys.ContainsKey("Customer"))
				{
					_Customer = Customer.FindByKey(CustomerID);
					Dirtys.Add("Customer", true);
				}
				return _Customer;
			}
			set { _Customer = value; }
		}
		#endregion

		#region 扩展查询
		/// <summary>
		/// 根据主键查询一个交易记录实体对象用于表单编辑
		/// </summary>
		///<param name="__ID">编号</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static Record FindByKeyForEdit(Int32 __ID)
		{
			Record entity=Find(new String[]{_.ID}, new Object[]{__ID});
			if (entity == null)
			{
				entity = new Record();
			}
			return entity;
		}     

		/// <summary>
		/// 根据编号查找
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static Record FindByID(Int32 id)
		{
			return Find(_.ID, id);
			// 实体缓存
			//return Meta.Cache.Entities.Find(_.ID, id);
			// 单对象缓存
			//return Meta.SingleCache[id];
		}

        /// <summary>
        /// 根据机器编号查找
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Record FindByMachineID(Int32 id)
        {
            return Find(_.MachineID, id);
            // 实体缓存
            //return Meta.Cache.Entities.Find(_.ID, id);
            // 单对象缓存
            //return Meta.SingleCache[id];
        }

		/// <summary>
		/// 根据名称查找
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static Record FindByName(String name)
		{
			return Find(_.Name, name);
			// 实体缓存
			//return Meta.Cache.Entities.Find(_.Name, name);
			// 单对象缓存
			//return Meta.SingleCache[name];
		}
		#endregion

		#region 高级查询
        /// <summary>
        /// 查询满足条件的记录集，分页、排序
        /// </summary>
        /// <param name="name"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>实体集</returns>
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public static EntityList<Record> Search(String name, String groups, String customer, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindAll(SearchWhere(name, groups, customer), orderClause, null, startRowIndex, maximumRows);
        }

        /// <summary>
        /// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
        /// </summary>
        /// <param name="name"></param>
        /// <param name="orderClause">排序，不带Order By</param>
        /// <param name="startRowIndex">开始行，0开始</param>
        /// <param name="maximumRows">最大返回行数</param>
        /// <returns>记录数</returns>
        public static Int32 SearchCount(String name, String groups, String customer, String orderClause, Int32 startRowIndex, Int32 maximumRows)
        {
            return FindCount(SearchWhere(name, groups, customer), null, null, 0, 0);
        }

        /// <summary>
        /// 构造搜索条件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static String SearchWhere(String name, String groups, String customer)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1=1");

            if (!String.IsNullOrEmpty(name)) sb.AppendFormat(" And {0} like '%{1}%'", _.Name, name.Replace("'", "''"));
            if (!String.IsNullOrEmpty(groups)) sb.AppendFormat(" And {0} like '%{1}%'", _.Groupings, groups.Replace("'", "''"));
            if (!String.IsNullOrEmpty(customer))
            {
                List<Customer> list = Customer.Search(customer, null, null, null, 0, 0);
                if (list != null && list.Count > 0)
                {
                    String ids = String.Empty;
                    ids = String.Join(",", list.ConvertAll<String>(delegate(Customer c) { return c.ID.ToString(); }).ToArray());
                    sb.AppendFormat(" And {0} in ({1})", _.CustomerID, ids);
                }
                else sb.AppendFormat(" And {0}=-1", _.CustomerID);
            }

            if (sb.ToString() == "1=1")
                return null;
            else
                return sb.ToString();
        }
		#endregion

		#region 扩展操作
		#endregion

		#region 业务
		#endregion
	}
}